package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEEDS_ZSET_KEY;

@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;


    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在!");
        }
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        isBlogLiked(blog);

        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) return;  // 用户未登录无需查询点赞
        String key = BLOG_LIKED_KEY + blog.getId();
//        Boolean isLiked = stringRedisTemplate.opsForSet().isMember(key, blog.getId().toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, blog.getId().toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());

            isBlogLiked(blog);

        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2. 判断是否点赞
        String key = BLOG_LIKED_KEY + id;
//        Boolean isLiked = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        // 3.1 未点赞，数据库 +1，保存 redis 的 set 集合中
        if (score == null) {
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
//                stringRedisTemplate.opsForSet().add(key,userId.toString());
                // 时间戳作分数
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 3.2 已点赞，数据库 -1，删除 redis 的 set 中移除
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
//                stringRedisTemplate.opsForSet().remove(key,userId.toString());
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    // 排行榜
    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        // 1. 查询 top 5
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        // 2. 解析用户ID
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String orderByString = StrUtil.join(",", ids);
        // 3. 根据用户 ID，查询用户，再返回
        List<UserDTO> userDTOS =
                userService.query().in("id", ids)
                        .last("ORDER BY FIELD(id," + orderByString + ")")
                        .list()
                        .stream()
                        .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                        .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        // 保存探店博文
        boolean isSaveSuccess = save(blog);
        if (!isSaveSuccess) {
            return Result.fail("新增笔记失败！");
        }
        // 查询笔记作者的所有粉丝
        List<Follow> follow_user_id = followService.query().eq("follow_user_id", userId).list();
        // 推送笔记 id 给所有粉丝
        for (Follow follow : follow_user_id) {
            // 获取粉丝ID
            Long fansId = follow.getUserId();
            // 推送到 redis 的 sorted set
            String key = FEEDS_ZSET_KEY + fansId;
            stringRedisTemplate.opsForZSet()
                    .add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.1 查询收件箱
        String key = FEEDS_ZSET_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples =
                stringRedisTemplate.opsForZSet()
                        .reverseRangeByScoreWithScores(
                                key, 0, max, offset, 2);
        // 2.2 非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 3. 解析数据：blogId, miniTime, offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long miniTime = 0;
        int os = 1;
        // 3.0 遍历
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // 3.1 获取 id
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            // 3.2 offset
            if (time == miniTime) {
                os++;
            } else {
                // 3.3 获取 miniTime
                miniTime = time;
                os = 1;
            }
        }
        // 4. 根据 blogId 查询 博客数据
        String idsStr = StrUtil.join(",", ids);
        List<Blog> blogList = query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idsStr + ")")
                .list();
        // 4.1 每次查询博客数据的时候，还要做判断点赞（之前实现的业务）
        for (Blog blog : blogList) {
            isBlogLiked(blog);
        }
        // 5. 封装返回
        return Result.ok(ScrollResult.builder()
                .list(blogList)
                .miniTime(miniTime)
                .offset(os)
                .build());
    }
}
